package com.jiazhong.mingxing.boot.boot04.test;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.concurrent.TimeUnit;

@SpringBootTest
@Slf4j
public class StringApp {
    // 1. 引入模版类
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    // 1. 存放
    @Test
    public void a() {
        // 2. 产生对string容器操作的类
        ValueOperations<String, String> forValue = stringRedisTemplate.opsForValue();
        forValue.set("A", "aa");
        forValue.set("B", "bb");
        forValue.set("C", "1");
        forValue.set("D", "dd");
        forValue.set("E", "ee");
        forValue.set("A", "aa2");
        // 存在就覆盖，不存在就没效果
        forValue.setIfPresent("B", "bb2");
        forValue.setIfPresent("F", "ff");
        // 存在没效果，不存在就添加
        forValue.setIfAbsent("D", "dd2");
        forValue.setIfAbsent("G", "gg");
        forValue.set("H", "hh", 1, TimeUnit.DAYS);
    }

    // 2. 获取
    @Test
    public void b() {
        ValueOperations<String, String> forValue = stringRedisTemplate.opsForValue();
        String a = forValue.get("A");
        String i = forValue.get("I");
        log.info("a={}, i={}", a, i);
        String d = forValue.getAndSet("D", "dd2");
        log.info("d={}", d);
        String g = forValue.getAndDelete("G");
        log.info("g={}", g);
        String b = forValue.getAndExpire("B", 2, TimeUnit.HOURS);
        log.info("b={}", b);
    }

    // 3. 其他
    @Test
    public void c() {
        ValueOperations<String, String> forValue = stringRedisTemplate.opsForValue();
        stringRedisTemplate.delete("D");
        forValue.increment("C",3); // +3
        forValue.increment("C"); // +1
        forValue.decrement("C"); // -1
        forValue.decrement("C",2); // -2
        forValue.append("A","1234567890");
    }
}
